import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutterapp/config.dart';
import 'package:flutterapp/page/utils/common_toast.dart';
import 'package:flutterapp/page/utils/scopoed_model_helper.dart';
import 'package:flutterapp/routes.dart';
import 'package:flutterapp/scoped_model/auth.dart';

class DioHttp {
  Dio _client;

  BuildContext context;

  static DioHttp of(BuildContext context) {
    return DioHttp._internal(context);
  }

  DioHttp._internal(BuildContext context) {
    if (_client == null || context != this.context) {
      this.context = context;
      var options = BaseOptions(
          baseUrl: Config.BaseUrl,
          //连接超时
          connectTimeout: 1000 * 10,
          //接受超时
          receiveTimeout: 1000 * 3,
          extra: {'context': context});
      //登录过期
      Interceptor interceptor = InterceptorsWrapper(onResponse: (Response res) {
        if (null == res) return res;
        var status = json.decode(res.toString())['status'];
        if (404 == status) {
          CommonToast.showToast('接口地址错误!!!:${res.request.uri}');
          return res;
        }

        if (status.toString().startsWith('4')) {
          //判断接口开始是否是4开头,是的话就是token过期
          ScopedModelHelper.getModel<AuthModel>(context).logout();
          //获取当前页面的路由............
          if (ModalRoute.of(context).settings.name == Routes.loading) {
            return res;
          }
          ;
          CommonToast.showToast("登录过期");
          //跳转到登录也
          Navigator.of(context).pushNamed(Routes.login);
          return res;
        }

        return res;
      });
      var client = Dio(options);
      client.interceptors.add(interceptor);
      //登录过期------------------------------------------
      this._client = client;
    }
  }

  //封装get方法
  Future<Response<Map<String, dynamic>>> get(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(headers: {'Authorization': token});
    //路径 token 参数
    return await _client.get(path, queryParameters: params, options: options);
  }

  //封装post方法
  Future<Response<Map<String, dynamic>>> post(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(headers: {'Authorization': token});
    //路径 token 参数
    return await _client.post(path, data: params, options: options);
  }

  //封装postFormData方法
  Future<Response<Map<String, dynamic>>> postFormData(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(
        //contentType: ContentType.parse('multipart/form-data'),
        headers: {'Authorization': token});

    //路径 token 参数
    return await _client.post(path, data: params, options: options);
  }
}
